<template>
  <view class="container">
    <!-- 选项卡导航 -->
    <view class="tabs">
      <view v-for="(tab, index) in tabs" :key="index" :class="['tab-item', { 'active': current === index }]"
        @click="current = index">
        {{ tab }}
      </view>
    </view>

    <!-- 货源信息的内容 -->
    <view v-if="current === 0" class="content-section">
      <view class="form-item">
        <view class="label">货源线路 <text class="required">*</text></view>
        <view class="picker-group">
          <view class="picker-row">
            <picker mode="selector" :range="loadingPlaces" range-key="name" @change="onLoadingPlaceChange"
              class="address-picker">
              <view class="picker">
                {{ formData.shippingaddress || '请选择装货地' }}
                <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
              </view>
            </picker>
            <text class="address-book" @click="openAddressBook('loading')">地址薄</text>
          </view>
          <view class="picker-row">
            <picker mode="selector" :range="unloadingPlaces" range-key="name" @change="onUnloadingPlaceChange"
              class="address-picker">
              <view class="picker">
                {{ formData.unloadingaddress || '请选择卸货地' }}
                <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
              </view>
            </picker>
            <text class="address-book" @click="openAddressBook('unloading')">地址薄</text>
          </view>
        </view>
        <view v-if="showConfirmRoute" class="confirm-btn" @click="confirmRoute">确定</view>
      </view>

      <view class="form-item">
        <view class="label">运输信息 <text class="required">*</text></view>
        <view class="input-group">
          <picker mode="selector" :range="cargoOptions" range-key="name" @change="onCargoChange">
            <view class="picker">
              {{ formData.cargoname || '请选择货物名称' }}
              <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
            </view>
          </picker>
          <input type="number" placeholder="请输入运输总量 吨" v-model="formData.totalweight" class="input" />
          <input type="number" placeholder="请输入运费单价 元/吨" v-model="formData.unitprice" class="input" />
          <view class="picker-container">
            <picker mode="selector" :range="suppliers" range-key="name" @change="onSupplierChange">
              <view class="picker">
                {{ formData.shipperid || '请选择供应商' }}
                <uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
              </view>
            </picker>
            <text class="address-book" @click="openSupplierList">选择</text>
          </view>
        </view>
      </view>

      <button class="primary-btn" @click="validateAndNext">下一步</button>
    </view>

    <!-- 接单条件的内容 -->
    <view v-if="current === 1" class="content-section">
      <view class="form-card">
        <text class="form-title">货源期限 *</text>
        <view class="date-group">
          <view class="date-item">
            <text>开始时间</text>
            <picker mode="date" :value="formData.startDate" @change="onStartDateChange">
              <view class="picker">{{ formData.startDate || '请选择日期' }}</view>
            </picker>
          </view>
          <view class="date-item">
            <text>结束时间</text>
            <picker mode="date" :value="formData.endDate" @change="onEndDateChange">
              <view class="picker">{{ formData.endDate || '请选择日期' }}</view>
            </picker>
          </view>
        </view>
      </view>

      <view class="form-card">
        <view class="switch-container">
          <view class="switch-label">
            <text class="title">专属货源</text>
            <text class="description">仅被指定分组的车辆可以接单</text>
          </view>
          <switch :checked="formData.isExclusiveSource" @change="onSwitchChange" active-color="#007aff"></switch>
        </view>
        <button v-if="formData.isExclusiveSource" class="secondary-btn" @click="addTransportTeam">添加运输车队</button>
      </view>

      <view class="form-card" v-if="formData.isExclusiveSource && formData.selectedTeams.length > 0">
        <text class="form-title">已选择的车队</text>
        <view class="team-item" v-for="(team, index) in formData.selectedTeams" :key="team.id">
          <text>{{ team.name }}</text>
          <text class="remove-btn" @click="removeTeam(index)">删除</text>
        </view>
      </view>

      <view class="form-card">
        <text class="form-title">费用信息</text>
        <text class="form-subtitle">运费结算时自动扣除</text>
        <input type="number" placeholder="司机服务费率 %" v-model="formData.driverServiceRate" class="input" />
        <input type="number" placeholder="油费  元/车" v-model="formData.fuelCost" class="input" />
      </view>

      <button class="primary-btn" @click="validateAndNext">下一步</button>
    </view>

    <!-- 预约确认的内容 -->
    <view v-if="current === 2" class="content-section">
      <view class="confirmation-card">
        <text class="section-title">货源信息确认</text>
        <view class="info-item">
          <text class="info-label">运输线路:</text>
          <text class="info-value">{{ formData.shippingaddress }} → {{ formData.unloadingaddress }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">货物信息:</text>
          <text class="info-value">{{ formData.cargoname }} {{ formData.totalweight }}吨</text>
        </view>
        <view class="info-item">
          <text class="info-label">运费单价:</text>
          <text class="info-value">{{ formData.unitprice }}元/吨</text>
        </view>
        <view class="info-item">
          <text class="info-label">供应商:</text>
          <text class="info-value">{{ formData.supplierName }}</text>
        </view>

        <text class="section-title" style="margin-top: 40rpx;">接单条件确认</text>
        <view class="info-item">
          <text class="info-label">运输期限:</text>
          <text class="info-value">{{ formData.starttime }} 至 {{ formData.endtime }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">专属货源:</text>
          <text class="info-value">{{ formData.isExclusiveSource ? '是' : '否' }}</text>
        </view>
        <view class="info-item" v-if="formData.isExclusiveSource && formData.selectedTeams.length > 0">
          <text class="info-label">指定车队:</text>
          <text class="info-value">{{ formData.selectedTeams.map(t => t.name).join(', ') }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">司机服务费率:</text>
          <text class="info-value">{{ formData.driverServiceRate }}%</text>
        </view>
        <view class="info-item">
          <text class="info-label">油费:</text>
          <text class="info-value">{{ formData.fuelCost }}元/车</text>
        </view>

        <button class="primary-btn" @click="submitAllData">确认发布货源</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { http } from '../../../config/request.js';
import { onLoad } from '@dcloudio/uni-app';

const current = ref(0);
const tabs = ref(['货源信息', '接单条件', '预约确认']);

// 表单数据
const formData = ref({
  // 货源信息
  shippingaddress: "",
  unloadingaddress: "",
  cargoname: "",
  totalweight: "",
  unitprice: 0.0,
  supplierId: "",
  shipperid: "",
  
  // 接单条件
  startDate: '',
  endDate: '',
  isExclusiveSource: false,
  driverServiceRate: '',
  fuelCost: '',
  selectedTeams: [],
  
  // 确认路由
  confirmedRoute: { loading: '', unloading: '' }
});

// 选择器索引
const loadingPlaceIndex = ref(-1);
const unloadingPlaceIndex = ref(-1);
const cargoIndex = ref(-1);
const supplierIndex = ref(-1);

// 选择器选项
const loadingPlaces = ref([]);
const unloadingPlaces = ref([]);
const cargoOptions = ref([]);
const suppliers = ref([]);

// UI状态
const showConfirmRoute = ref(false);

// 从后端获取数据
const fetchData = async () => {
  try {
    const res = await http({
      url: '/selectHuoYuan',
      method: 'post'
    });
    
    if (res.code === 20041) {
      // 处理装货地和卸货地数据
      loadingPlaces.value = res.shuju.map(item => ({
        name: item.shippingaddress,
        id: item.id
      }));
      
      unloadingPlaces.value = res.shuju.map(item => ({
        name: item.unloadingaddress || item.shippingaddress,
        id: item.id
      }));
      
      // 处理货物选项数据 - 去重
      const uniqueCargos = [];
      const cargoMap = new Map();
      res.shuju.forEach(item => {
        if (!cargoMap.has(item.cargoname)) {
          cargoMap.set(item.cargoname, true);
          uniqueCargos.push({
            name: item.cargoname,
            id: item.id
          });
        }
      });
      cargoOptions.value = uniqueCargos;
      
      // 处理供应商数据 - 去重
      const uniqueSuppliers = [];
      const supplierMap = new Map();
      res.shuju.forEach(item => {
        if (item.shipperid && !supplierMap.has(item.shipperid)) {
          supplierMap.set(item.shipperid, true);
          uniqueSuppliers.push({
            name: item.shippername || `供应商${item.shipperid}`,
            id: item.shipperid
          });
        }
      });
      suppliers.value = uniqueSuppliers;
    } else {
      throw new Error(res.message || '获取数据失败');
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    });
  }
};

// 方法定义
const onLoadingPlaceChange = (event) => {
  loadingPlaceIndex.value = event.detail.value;
  formData.value.shippingaddress = loadingPlaces.value[loadingPlaceIndex.value]?.name || '';
  showConfirmRoute.value = true;
};

const onUnloadingPlaceChange = (event) => {
  unloadingPlaceIndex.value = event.detail.value;
  formData.value.unloadingaddress = unloadingPlaces.value[unloadingPlaceIndex.value]?.name || '';
  showConfirmRoute.value = true;
};

const onCargoChange = (event) => {
  cargoIndex.value = event.detail.value;
  formData.value.cargoname = cargoOptions.value[cargoIndex.value]?.name || '';
};

const onSupplierChange = (event) => {
  supplierIndex.value = event.detail.value;
  const selectedSupplier = suppliers.value[supplierIndex.value];
  if (selectedSupplier) {
    formData.value.supplierId = selectedSupplier.id;
    formData.value.shipperid = selectedSupplier.shipperid;
  }
};

const openAddressBook = (type) => {
  uni.navigateTo({
    url: '/pages/sourceofgoods/pageinfo/address'
  });
};

const openSupplierList = () => {
  uni.navigateTo({
    url: '/pages/Supplier/SupplierList',
    events: {
      onSelectSupplier: (supplier) => {
        suppliers.value.push(supplier);
        supplierIndex.value = suppliers.value.length - 1;
        formData.value.supplierId = supplier.id;
        formData.value.shipperid = supplier.shipperid;
      }
    }
  });
};

const confirmRoute = () => {
  formData.value.confirmedRoute = {
    loading: formData.value.shippingaddress,
    unloading: formData.value.unloadingaddress
  };
  showConfirmRoute.value = false;
  uni.showToast({
    title: '路线已确认',
    icon: 'success'
  });
};

const onStartDateChange = (e) => {
  formData.value.startDate = e.detail.value;
};

const onEndDateChange = (e) => {
  formData.value.endDate = e.detail.value;
};

const onSwitchChange = (e) => {
  formData.value.isExclusiveSource = e.detail.value;
};

const addTransportTeam = () => {
  uni.navigateTo({
    url: '/pages/sourceofgoods/pageinfo/xuanzchedui',
    events: {
      onSelectTeam: (team) => {
        if (!formData.value.selectedTeams.some(t => t.id === team.id)) {
          formData.value.selectedTeams.push(team);
        } else {
          uni.showToast({
            title: '该车队已添加',
            icon: 'none'
          });
        }
      }
    }
  });
};

const removeTeam = (index) => {
  formData.value.selectedTeams.splice(index, 1);
};

const validateGoodsInfo = () => {
  if (!formData.value.shippingaddress || !formData.value.unloadingaddress) {
    uni.showToast({
      title: '请选择完整的运输路线',
      icon: 'none'
    });
    return false;
  }
  if (!formData.value.cargoname || !formData.value.totalweight || !formData.value.unitprice) {
    uni.showToast({
      title: '请填写完整的运输信息',
      icon: 'none'
    });
    return false;
  }
  return true;
};

const validateOrderConditions = () => {
  if (!formData.value.startDate || !formData.value.endDate) {
    uni.showToast({
      title: '请选择完整的运输期限',
      icon: 'none'
    });
    return false;
  }
  if (new Date(formData.value.endDate) < new Date(formData.value.startDate)) {
    uni.showToast({
      title: '结束时间不能早于开始时间',
      icon: 'none'
    });
    return false;
  }
  return true;
};

const validateAndNext = () => {
  if (current.value === 0) {
    if (!validateGoodsInfo()) return;
    current.value = 1;
  } else if (current.value === 1) {
    if (!validateOrderConditions()) return;
    current.value = 2;
  }
};

const submitAllData = async () => {
  try {
    uni.showLoading({ title: '发布中...' });

    const payload = {
      // 货源信息
      shippingaddress: formData.value.shippingaddress,
      unloadingaddress: formData.value.unloadingaddress,
      cargoname: formData.value.cargoname,
      totalweight: formData.value.totalweight,
      unitprice: formData.value.unitprice,
      supplierId: formData.value.supplierId,
      
      // 接单条件
      startDate: formData.value.startDate,
      endDate: formData.value.endDate,
      isExclusiveSource: formData.value.isExclusiveSource,
      driverServiceRate: formData.value.driverServiceRate,
      fuelCost: formData.value.fuelCost,
      teamIds: formData.value.selectedTeams.map(team => team.id)
    };

    console.log('提交所有数据:', payload);
    
    const res = await http({
      url: '/addfreightsources',
      method: 'POST',
      data: payload
    });

    if (res.code === 200) {
      uni.hideLoading();
      uni.showToast({
        title: '货源发布成功',
        icon: 'success'
      });

      resetForm();

      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      throw new Error(res.message || '发布失败');
    }
  } catch (error) {
    uni.hideLoading();
    console.error('发布货源失败:', error);
    uni.showToast({
      title: error.message || '发布失败',
      icon: 'none'
    });
  }
};

const resetForm = () => {
  formData.value = {
    shippingaddress: "",
    unloadingaddress: "",
    cargoname: "",
    totalweight: "",
    unitprice: 0.0,
    supplierId: "",
    supplierName: "",
    startDate: '',
    endDate: '',
    isExclusiveSource: false,
    driverServiceRate: '',
    fuelCost: '',
    selectedTeams: [],
    confirmedRoute: { loading: '', unloading: '' }
  };
  current.value = 0;
};

onMounted(() => {
  fetchData();
});

onLoad(() => {
  // 如果有需要从路由参数中获取的数据可以在这里处理
});
</script>

<style lang="scss" scoped>
/* 样式保持不变，与之前相同 */
.container {
  padding: 20rpx;
  background-color: #f7f7f7;
  min-height: 100vh;
  box-sizing: border-box;
}

.tabs {
  display: flex;
  justify-content: space-around;
  width: 100%;
  margin-bottom: 30rpx;
  border-bottom: 2rpx solid #e5e5e5;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx 0;
}

.tab-item {
  font-size: 28rpx;
  color: #666;
  padding: 10rpx 20rpx;
  position: relative;

  &.active {
    color: #007aff;
    font-weight: bold;

    &::after {
      content: '';
      position: absolute;
      bottom: -22rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 60rpx;
      height: 4rpx;
      background-color: #007aff;
      border-radius: 2rpx;
    }
  }
}

.content-section {
  width: 100%;
}

.form-item,
.form-card,
.confirmation-card {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.label,
.form-title,
.section-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  font-weight: bold;
  display: block;
}

.required {
  color: #f56c6c;
  margin-left: 8rpx;
  font-size: 24rpx;
}

.picker-group {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.picker-row,
.picker-container {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.address-picker {
  flex: 1;
}

.picker {
  font-size: 28rpx;
  color: #666;
  padding: 20rpx;
  background-color: #f9f9f9f9;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-book {
  font-size: 24rpx;
  color: #007aff;
  padding: 20rpx;
  white-space: nowrap;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.input {
  font-size: 28rpx;
  color: #666;
  padding: 20rpx;
  background-color: #f9f9f9f9;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
}

.form-subtitle {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-bottom: 20rpx;
}

.date-group {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.date-item {
  display: flex;
  align-items: center;
  justify-content: space-between;

  text {
    font-size: 28rpx;
    color: #666;
  }
}

.switch-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.switch-label {
  flex: 1;

  .title {
    font-size: 28rpx;
    color: #333;
    display: block;
    margin-bottom: 10rpx;
  }

  .description {
    font-size: 24rpx;
    color: #999;
    display: block;
  }
}

.primary-btn {
  background-color: #007aff;
  color: #fff;
  font-size: 30rpx;
  padding: 20rpx;
  border-radius: 8rpx;
  text-align: center;
  margin-top: 40rpx;
  width: 100%;
  border: none;
}

.secondary-btn {
  background-color: #f0f0f0;
  color: #007aff;
  font-size: 28rpx;
  padding: 16rpx;
  border-radius: 8rpx;
  text-align: center;
  width: 100%;
  border: none;
  margin-top: 20rpx;
}

.confirm-btn {
  background-color: #007aff;
  color: #fff;
  font-size: 26rpx;
  padding: 10rpx 20rpx;
  border-radius: 6rpx;
  margin-top: 10rpx;
  align-self: flex-end;
}

.info-item {
  display: flex;
  margin-bottom: 20rpx;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #eee;

  .info-label {
    font-size: 28rpx;
    color: #666;
    width: 150rpx;
  }

  .info-value {
    font-size: 28rpx;
    color: #333;
    flex: 1;
  }
}

.team-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #eee;

  text {
    font-size: 28rpx;
    color: #333;
  }

  .remove-btn {
    font-size: 24rpx;
    color: #ff5722;
    cursor: pointer;
  }
}

@media (min-width: 768px) {
  .container {
    padding: 40rpx;
    max-width: 750px;
    margin: 0 auto;
  }

  .tabs {
    padding: 30rpx 0;
  }

  .tab-item {
    font-size: 32rpx;
    padding: 15rpx 30rpx;
  }

  .form-item,
  .form-card,
  .confirmation-card {
    padding: 40rpx;
  }

  .label,
  .form-title,
  .section-title {
    font-size: 32rpx;
  }

  .input,
  .picker {
    font-size: 30rpx;
    padding: 25rpx;
  }

  .primary-btn {
    font-size: 34rpx;
    padding: 25rpx;
  }
}
</style>